﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Web.Mvc;
using LibraryCatalog.Models;
using PropertyExpression.Common;
using PropertyExpression.ControllableQuery;

namespace LibraryCatalog.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new IndexModel(GetBooks()));
        }

        public ActionResult AddBook()
        {
            return PartialView("EditBook", new EditBookModel(GetLibraries()));
        }

        public ActionResult EditBook(string bookId)
        {
            var book = Query<IBook>.New(new {
                BookId = int.Parse(bookId)
            }, "SELECT * FROM Book WHERE BookId = @BookId").Result().SingleOrDefault();
            if (book == null)
                return PartialView("BooksGrid", new BookGridModel(GetBooks(), showAlreadyDeleted: true));
            return PartialView(new EditBookModel(GetLibraries(), book.AsOption()));
        }

        public ActionResult SaveBook(BookRequest request)
        {
            if (request.HasErrors)
                return PartialView("EditBook", new EditBookModel(GetLibraries(), request: request));
            var isNew = string.IsNullOrEmpty(request.BookId);
            NonQuery.New(new {
                isNew, param = new {
                    BookId = isNew ? default(int) : int.Parse(request.BookId), request.Name, request.Author,
                    request.Isbn, LibraryId = int.Parse(request.LibraryId)
                }
            }, "@p.InsertOrUpdate(\"Book\")").Execute();
            return PartialView("BooksGrid", new BookGridModel(GetBooks(), closeDialog: true));
        }

        public ActionResult DeleteBook(string bookId)
        {
            NonQuery.New(new {BookId = int.Parse(bookId)}, "@p.Delete(\"Book\")").Execute();
            return PartialView("BooksGrid", new BookGridModel(GetBooks()));
        }

        private static List<IBookInfo> GetBooks()
        {
            return Query<IBookInfo>.New(new {}, @"
SELECT  BookId, Book.Name, Author, Library.Name AS LibraryName
FROM    Book JOIN Library ON Book.LibraryId = Library.LibraryId
ORDER BY Book.Name").List();
        }

        private static List<ILibrary> GetLibraries()
        {
            return Query<ILibrary>.New(new {}, "SELECT * FROM Library ORDER BY Name").List();
        }

        static HomeController()
        {
            RegisterRazorConfiguration();
        }

        private static void RegisterRazorConfiguration([CallerFilePath] string filePath = "")
        {
            RazorConfiguration.Register(filePath, new [] {
                typeof(DB).Namespace
            }, MethodBase.GetCurrentMethod());
        }
    }
}